package club.monkeywood.transaction.ticket.dao;

import club.monkeywood.transaction.ticket.vo.Ticket;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

public interface TicketRepository extends JpaRepository<Ticket, Long> {
    Ticket findByOwner(Long owner);
    Ticket findByTicketNum(Long ticketNum);
    //Ticket findByTicketNumAndLockUser(Long ticketNum);

    //票锁定，分配给指定用户
    //刷新hibernate的一级缓存，同步数据库
    @Modifying(clearAutomatically = true)
    @Query("update ticket set lockUser=?1 where lockUser is NULL and owner is NULL and ticketNum=?2")
    int lockTicket(Long customerId, Long ticketNum);

    //票解锁，取消分配给指定用户
    //刷新hibernate的一级缓存，同步数据库
    @Modifying(clearAutomatically = true)
    @Query("update ticket set lockUser=NULL where lockUser is not NULL and ticketNum=?1")
    int unlockTicket(Long ticketNum);

    //票交付，将票设置为用户的票
    @Modifying
    @Query("update ticket set owner=?1, lockUser=null  where lockUser=?1 and ticketNum=?2")
    int moveTicket(Long customerId, Long ticketNum);

    //票取消交付
    //刷新hibernate的一级缓存，同步数据库
    @Modifying(clearAutomatically = true)
    @Query("update ticket set owner=NULL  where owner is not null and ticketNum=?1")
    int unmoveTicket(Long ticketNum);


}
